const getUserAvatar = require('../../utils/getUserAvatar')
const QR = require("../../utils/qrcode.js")

Page({
  data: {
    adPicUrl: ''
  },
  async onReady() {
    const that = this
    const qrCodeInfo = JSON.stringify({
      firstname: 'Felix',
      secondname: 'chan',
      age: 18,
      hobby: 'codeing, sport...etc'
    })

    await this.createQrCode(qrCodeInfo, 'qrCode', 350, 350)
    const qrcodeUrl = await this.canvasToTempUrl({ canvasId: 'qrCode' }, that)


    let avatarUrl = await this._getUserAvatarUrl()
    console.log(avatarUrl)

    const query = wx.createSelectorQuery()
    query.select('#myCanvas')
      .fields({
        node: true,
        size: true
      })
      .exec(async res => {
        const canvas = res[0].node
        const ctx = canvas.getContext('2d')
        canvas.width = 646;
        canvas.height = 989;
        _drawBackgroundColor()
        await _drawBackground('http://127.0.0.1:2828/static/images/test.jpg')
        _drawAvatar()   // 函数内部没有异步操作
        _drawGoodTitleText('这是一段测试文本')
        _drawShareText('对酒当歌, 人生几何！')
        _drawQrcode(qrcodeUrl)
        // 海报绘制完成, 将它转换成图片链接
        setTimeout(async () => {
          console.log(that)
          const adPicUrl = await this.canvasToTempUrl({ canvas }, that)
          console.log('adPicUrl', adPicUrl)

          this.setData({
            adPicUrl
          })
        }, 3000)

        function  _drawBackgroundColor() {
          ctx.save()
          ctx.beginPath()
          ctx.fillStyle = '#fff';
          ctx.fillRect(0, 0, 646, 989); 
          ctx.restore()
        }

        function _drawBackground (bgPicUrl) {
          return new Promise(async resolve => {
            const headerBgPicture = await _downLoadFileAndLoad(bgPicUrl)
            const picWidth = headerBgPicture.width
            const picHeight = headerBgPicture.height
            const containerWidth = canvas.width
            const containeHeight = 320
            const _calcSizeAndPosition = (picWidth, picHeight, containerWidth, containeHeight) => {
              const containerRatio = containerWidth / containeHeight // 计算容器的宽高比, 这里容器的宽为646, 高为320
              const picRatio = picWidth / picHeight
              if (picRatio === containerRatio) {
                // 如果图片的宽高比和容器的宽高比相等的话, 那我们让图片从(0, 0)w位置开始, 尺寸就是containerWidth和containeHeight
                return {
                  pos: {
                    x: 0,
                    y: 0
                  },
                  width: containerWidth,
                  height: containeHeight
                }
              } else if (picRatio < containerRatio) {
                // 如果图片的宽高比小于容器的宽高比的话, 我们要让图片的宽度和的容器的宽度相等, 这时候, 图片的高度就会超出容器, 我们需要调整起始点的坐标
                return {
                  pos: {
                    x: 0,
                    y: -(picHeight * (containerWidth / picWidth) - containeHeight) / 2
                  },
                  width: containerWidth,
                  height: picHeight * (containerWidth / picWidth)
                }
              } else if (picRatio > containerRatio) {
                // 如果图片的宽高比大于容器的宽高比的话, 我们要让图片的高度和的容器的高度相等, 这时候, 图片的宽度就会超出容器, 我们需要调整起始点的坐标
                return {
                  pos: {
                    x: -(picWidth * (containeHeight / picHeight) - containerWidth) / 2,
                    y: 0
                  },
                  width: picWidth * (containeHeight / picHeight),
                  height: containeHeight
                }
              }
            }
            const sizeAndPos = _calcSizeAndPosition(picWidth, picHeight, containerWidth, containeHeight)
            // console.log(sizeAndPos);

            ctx.save()
            // ctx.shadowOffsetX = 50;
            // // 阴影的y偏移
            // ctx.shadowOffsetY = 50;
            // // 阴影颜色
            // ctx.shadowColor = 'rgba(0,0,0,0.8)';
            // // 阴影的模糊半径
            // ctx.shadowBlur = 30;
            ctx.beginPath()
            // 绘制圆角矩形
            // ctx.moveTo(0, 15);
            // ctx.lineTo(0, 320);
            // ctx.lineTo(646, 320);
            // ctx.lineTo(646, 15);
            // ctx.arcTo(646, 0, 631, 0, 15);
            // ctx.lineTo(15, 0);
            // ctx.arcTo(0, 0, 0, 15, 15);
            // ctx.stroke()
            // ctx.fillStyle = 'rgba(255,0,0,1)'
            // ctx.fill();
            ctx.rect(0, 0, 646, 989);
            ctx.clip()
            ctx.drawImage(headerBgPicture, sizeAndPos.pos.x, sizeAndPos.pos.y, sizeAndPos.width, sizeAndPos.height)
            ctx.restore()
            resolve()
            console.log('背景图画完啦')
          })
        }

        async function _drawAvatar () {
          const avatar = await _downLoadFileAndLoad(avatarUrl)
          ctx.save()
          ctx.beginPath()
          ctx.arc(323, 320, 81, 0, 2 * Math.PI)
          ctx.strokeStyle = "#fff"
          ctx.lineWidth = 24
          ctx.stroke()
          ctx.clip()
          // ctx.fill()
          // 这里由于微信头像拿到的都是正方形的, 所以就没必要重新调整位置啦
          ctx.drawImage(avatar, 242, 239, 162, 162)
          ctx.restore()
        }

        function _drawGoodTitleText (text) {
          console.log('开始绘制商品标题啦')
          ctx.save()
          ctx.beginPath()
          ctx.font = 'normal 33px Arial';
          ctx.textAlign = 'center';
          ctx.textBaseline = 'bottom';
          ctx.fillStyle = '#666';
          // ctx.strokeText("Hello Canvas", 400, 400);
          ctx.fillText(text, 323, 483); 
          ctx.restore()
        }

        function _downLoadFileAndLoad(bgPicUrl) {
          return new Promise(resolve => {
            wx.downloadFile({
              url: bgPicUrl,
              success(res) {
                let image = canvas.createImage()
                image.src = res.tempFilePath;
                image.onload = function () {
                  resolve(image)
                }
              }
            })
          })
        }

        function _drawShareText (text) {
          console.log('开始分享标题')
          ctx.save()
          ctx.beginPath()
          ctx.font = 'bold 49px Arial';
          ctx.textAlign = 'center';
          ctx.textBaseline = 'bottom';
          ctx.fillStyle = '#000';
          ctx.fillText(text, 323, 582); 
          ctx.restore()
        }

        async function _drawQrcode (qrCodeUrl) {
          console.log('开始绘制二维码')
          let qrCode = await _downLoadFileAndLoad(qrCodeUrl)
          ctx.save()
          ctx.beginPath()
          ctx.rect(179, 627, 287, 287)
          ctx.clip()
          ctx.drawImage(qrCode, 174, 622, 298, 297)
          ctx.restore()
        }
      })
    
    
  },
  
  getuserinfo(res) {
    console.log(res)
  },

  createQrCode: function (content, canvasId, cavW, cavH) {
    //调用插件中的draw方法，绘制二维码图片
    QR.api.draw(content, canvasId, cavW, cavH)
  },
  
  //获取临时图片的url
  canvasToTempUrl: function (option, that) {
    return new Promise((resolve, reject) => {
      console.log(that)
      wx.canvasToTempFilePath({
        ...option,
        success: function (res) {
          const tempFilePath = res.tempFilePath;
          resolve(tempFilePath)
        },
        fail: function (err) {
          reject(err)
        }
      }, that)
    })
  },

  _getUserAvatarUrl () {
    return new Promise(resolve => {
      wx.getUserInfo({
        success: (res) => {
          resolve(res.userInfo.avatarUrl)
        }
      })
    })
  },

  _getUserInfo () {
    
  }
})